import {Card, Table, Button, Tooltip, InputNumber, Input, Form, Popconfirm} from 'antd';
import React, {Component} from "react";
import {connect} from "dva";
const ButtonGroup = Button.Group;
const EditableContext = React.createContext();

const data = [
  {
    key: 1,
    name: 'John Brown sr.',
    age: 60,
    address: 'New York No. 1 Lake Park',
    children: [
      {
        key: 11,
        name: 'John Brown',
        age: 42,
        address: 'New York No. 2 Lake Park',
      },
      {
        key: 12,
        name: 'John Brown jr.',
        age: 30,
        address: 'New York No. 3 Lake Park',
      },
      {
        key: 13,
        name: 'Jim Green sr.',
        age: 72,
        address: 'London No. 1 Lake Park',
      },
    ],
  },
  {
    key: 2,
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
    children: null
  },
];

// rowSelection objects indicates the need for row selection
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
  },
  getCheckboxProps: record => ({
    disabled: record.name === 'John Brown sr.', // Column configuration not to be checked
    name: record.name,
  }),
};

const rowClassName = (record, index) => {
  if(record.name === 'John Brown sr.'){
    return 'orderParent';
  }
}

class EditableCell extends Component {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, padding: 0}}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `Please Input ${title}!`,
                },
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}
@connect(({loading, global}) => ({
  tableLoading: loading.effects['global/fetchNotices'],
  notices: global.notices
}))
class NestTable extends Component {

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/fetchNotices',
    }).then(() => {
      console.log(this.props.notices)
    })
  }

  constructor(props) {
    super(props);
    this.state = {data, editingKey: ''};
    this.columns = [
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        width: '180px',
        editable: true,
      },
      {
        title: 'Age',
        dataIndex: 'age',
        key: 'age',
        width: '1200px',
        editable: true,
      },
      {
        title: 'Address',
        dataIndex: 'address',
        width: '1300px',
        key: 'address',
        editable: true,
      },
      {
        title: '操作',
        key: 'operation',
        fixed: 'right',
        width: '100px',
        render: (text, record) =>  {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <ButtonGroup>
              <EditableContext.Consumer>
                {form => (
                  <Tooltip placement="bottom" title="保存">
                    <Button size="small"  onClick={() => this.save(form, record.key)} icon="save"></Button>
                  </Tooltip>
                )}
              </EditableContext.Consumer>

              <Popconfirm title="Sure to cancel?" onConfirm={() => this.cancel(record.key)}>
                <Tooltip placement="bottom" title="撤回">
                  <Button size="small" icon="rollback"></Button>
                </Tooltip>
              </Popconfirm>
            </ButtonGroup>
          ) : (
            <ButtonGroup>
              <Tooltip placement="bottom" title="编辑">
                <Button disabled={editingKey !== ''} size="small" icon="edit" onClick={() => this.edit(record.key)}></Button>
              </Tooltip>
            </ButtonGroup>
          );
        },
      },
    ];
  }

  isEditing = record => record.key === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: '' });
  };

  save(form, key) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.data];
      debugger
      const index = newData.findIndex(item => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        this.setState({ data: newData, editingKey: '' });
      } else {
        newData.push(row);
        this.setState({ data: newData, editingKey: '' });
      }
    });
  }

  edit(key) {
    this.setState({ editingKey: key });
  }

  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <EditableContext.Provider value={this.props.form}>
        <Card bodyStyle={{padding: 0}}>
        <Table
          components={components}
          loading={this.props.tableLoading}
          columns={columns}
          rowSelection={rowSelection}
          dataSource={this.state.data}
          size="small"
          bordered
          rowClassName={rowClassName}
          scroll={{x: 'max-content'}}
          pagination={{
            onChange: this.cancel,
          }}
        />
        </Card>
      </EditableContext.Provider>
    );
  }
}

const EditableFormTable = Form.create()(NestTable);
export default EditableFormTable;
